package mwa.cs.cr.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.AddressDAO;
import mwa.cs.dao.CustomerDAO;
import mwa.cs.database.Database;

/**
 * Servlet implementation class CS22000
 */
public class CS22000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	//private int vnUserId;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS22000Srvl() {
        super();
    }

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		//vnUserId = 1;//(Integer) request.getSession().getAttribute("user_id");
		if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		}
		
	}
	
    @SuppressWarnings("unchecked")
    private void getDataTable (HttpServletRequest request, HttpServletResponse response) throws IOException {
		// columns for sorting data
		String[] vaColumns = { "account", "account", "account_old", "fname" };
	    int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
	    int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
	    String vaDraw = request.getParameter("sEcho");
	    int vnSortColumn = Integer.parseInt(request.getParameter("iSortCol_0")); // 0, 1, 2, 3
	    String vaSortDirection = request.getParameter("sSortDir_0"); // asc, desc
	    //String vaSearchTerm = request.getParameter("sSearch");
	    
	    boolean vbSearch = false;
	    String vaAccountSearching = request.getParameter("sSearch_0").trim();
	    String vaAccountOldSearching = request.getParameter("sSearch_1").trim();
	    String vaHomeNumberSearching = request.getParameter("sSearch_2").trim();
	    String vaNameSearching = request.getParameter("sSearch_3").trim();	    
	    if ((!vaAccountSearching.equals("") || !vaAccountOldSearching.equals("") 
	    		|| !vaHomeNumberSearching.equals("") || !vaNameSearching.equals("")))
	    		vbSearch = true;

	    // get data from database
	    int vnTotal = 0;
	    int vnTotalAfterFilter = 0;
	    List<Map<String, Object>> voResult = null;
	    Database db = new Database();
	    try {
	    	CustomerDAO voCustomerManagement = new CustomerDAO(db);
	    	vnTotal = voCustomerManagement.getAllCountCustomerBySiteId(vnSiteId);
	    	if (vnAmount == -1) {
	    		voResult = voCustomerManagement.findCustomerBySiteId(vnSiteId, vaColumns[vnSortColumn], vaSortDirection);
	    		vnTotalAfterFilter = vnTotal;
	    	} else if (vbSearch == true) {
	    		voResult = voCustomerManagement.findCustomerBySearching(vnSiteId, vaAccountSearching, 
	    				vaAccountOldSearching, vaHomeNumberSearching, vaNameSearching, 
	    				vaColumns[vnSortColumn], vaSortDirection, vnStart, vnStart + vnAmount);
	    		vnTotalAfterFilter = voCustomerManagement.getSearchingCountCustomer(vnSiteId, vaAccountSearching, 
	    				vaAccountOldSearching, vaHomeNumberSearching, vaNameSearching);
	    		vnTotal = vnTotalAfterFilter;
	    	} else {
	    		voResult = voCustomerManagement.findCustomerByLength(vnSiteId, 
	    				vaColumns[vnSortColumn], vaSortDirection, vnStart, vnStart + vnAmount);
	    		vnTotalAfterFilter = vnTotal;
	    	}
	    } finally {
	    	db.close();
	    }  
	    // prepare data to show in dataTable
	    PrintWriter VoOut = response.getWriter();
	    // set sequence
	    int[] vnSequence = new int[voResult.size()];
	    for (int i = 1; i <= voResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;
	    Database db2 = new Database();
	    try {
	    	AddressDAO voAddress = new AddressDAO(db2);
	    	JSONObject voObject = new JSONObject();
		    JSONArray voListData = new JSONArray();
		    for (int i = 0; i < voResult.size(); i++) {
		    	Map<String, Object> voTmp = voResult.get(i);	
				JSONArray voArray = new JSONArray();
				voArray.add(vnSequence[i]);
				voArray.add((String) voTmp.get("ACCOUNT"));
				voArray.add((String) voTmp.get("ACCOUNT_OLD"));
				// Name
	            String vaPName = (String) voTmp.get("PNAME");
	            if (vaPName == null) vaPName = "";
	            String vaFName = (String) voTmp.get("FNAME");
	            if (vaFName == null) vaFName = "";
	            String vaLName = (String) voTmp.get("LNAME");
	            if (vaLName == null) vaLName = "";
	            voArray.add(vaPName + " " + vaFName + " " + vaLName);
	            // Address
	            String vaHomeNumber = (String) voTmp.get("HOME_NUMBER");
	            if (vaHomeNumber == null) vaHomeNumber = "";
	            String vaAddress = (String) voTmp.get("ADDRESS");
	            if (vaAddress == null) vaAddress = "";
	            String vaProvinceCode = (String) voTmp.get("PROVINCE_CODE");
	            String vaProvince = voAddress.getProvinceName(vaProvinceCode);
	            if (vaProvince == null) vaProvince = "";
	            String vaDistrictCode = (String) voTmp.get("DISTRICT_CODE");
	            String vaDistrict = voAddress.getDistrictName(vaProvinceCode, vaDistrictCode);
	            if (vaDistrict == null) vaDistrict = "";
	            String vaCityCode = (String) voTmp.get("CITY_CODE");
	            String vaCity = voAddress.getCityName(vaProvinceCode, vaDistrictCode, vaCityCode);
	            if (vaCity == null) vaCity = "";
	            String vaPostCode = (String) voTmp.get("POST_CODE");
	            if (vaPostCode == null) vaPostCode = "";
	            voArray.add(vaHomeNumber + " " + vaAddress + " " 
	            + vaCity + " " + vaDistrict + " " + vaProvince + " " + vaPostCode);
	            // data for button's action
				voArray.add((String) voTmp.get("ACCOUNT"));
				// adding array data into list
	            voListData.add(voArray);
		    }
		    voObject.put("sEcho", Integer.parseInt(vaDraw));
		    voObject.put("iTotalRecords", vnTotal);
	        voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
	        voObject.put("aaData", voListData);
	        VoOut.print(voObject.toJSONString());
	    } finally {
	    	db2.close();
			VoOut.close();
		}
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}
	
}
